from google.appengine.ext import db

from google.appengine.ext.db import djangoforms
from google.appengine.ext.db import polymodel
from models.Users import *
import logging

class Message(polymodel.PolyModel):
    """This is the base class for messages. It will serve as the 
    main message and will have a one-to-many relationship with
    replies. Has a one-to-one relation with Users.
    
    To provide the necessary query abilities we are going to use 
    integers to refer to relationships rather than the native google 
    reference proptery as the native property does not allow for queries such 
    as select * from child where child.parent = parent.key. 
    However if we use an integer we can do select * from child where 
    child.parent = parent.key().id()
    """
    
    message = db.StringProperty(required=True,multiline=True)
    author = db.IntegerProperty(required=True,default=-1)
    date_published = db.DateTimeProperty(required=True, auto_now_add=True)
    subject = db.StringProperty(required=False, multiline=False,default='')
    topic = db.IntegerProperty(required=True,default = -1)
    parent_id = db.IntegerProperty(required=True, default=-1)
    

    
    # overiding the default delete method to delete all children if the 
    # parent message is removed.
    def delete(self):
      """docstring for delete"""
      if self.parent_id != -1:
        logging.error("We are deleting an Item")
        polymodel.PolyModel.delete(self)
      else: 
        query = Message.all()
        query.filter('parent_id = ', self.key().id())
        
        # loop through all the replies to delete them
        for item in query:
          logging.error("We have entered the Loop\n" + str(type(item)))
          polymodel.PolyModel.delete(item)

        # now delete the parent
        polymodel.PolyModel.delete(self)
        
        

#class NewMessage(Message):
    #title = db.StringProperty(required=True)

class ReplyMessage(Message):
    myParent = db.ReferenceProperty(required=False)

class MessageForm(djangoforms.ModelForm):
    class Meta:
        model = Message 
        exclude = ['_class','author','parent_id','topic']

#class NewMessageForm(djangoforms.ModelForm):
#    class Meta:
 #       model = NewMessage
  #x      exclude = ['_class','author']

class ReplyMessageForm(djangoforms.ModelForm):
    class Meta:
        model = Message
        exclude = ['_class','author','parent_id','subject','topic']
